﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Net.Http;
using System.Net.Http.Headers;
using MyCities.Models;
using System.Threading.Tasks;

namespace MyCities.Views
{
    public partial class SortPage : PhoneApplicationPage
    {
        public SortPage()
        {
            InitializeComponent();

            // Begin downloading and binding data -> methods defined below
            try
            {
                ProcessData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK);
                SortProgressBar.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        // method to bind data to controls
        public async void ProcessData()
        {
            // display progress bar
            SortProgressBar.Visibility = System.Windows.Visibility.Visible;

            // binding data
            PopLLS.ItemsSource = await DownloadData<CityPopulation>("city/population");
            AreaLLS.ItemsSource = await DownloadData<CityArea>("city/area");
            DensityLLS.ItemsSource = await DownloadData<CityDensity>("city/density");

            // collapse progress bar
            SortProgressBar.Visibility = System.Windows.Visibility.Collapsed;
        }

        // method to download data
        public async Task<List<T>> DownloadData<T>(string query)
        {
            HttpClient client = new HttpClient();

            var response = await DownloadClient.GetData(client, query);

            if (response.IsSuccessStatusCode)
            {
                var itemList = await response.Content.ReadAsAsync<List<T>>();
                return itemList;
            }
            else
            {
                string output = response.StatusCode + " : " + response.ReasonPhrase;
                throw new HttpRequestException(output);
            }
        }
    }
}